package com.llly.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.llly.client.OrderFeignClient;
import com.llly.client.ProductFeignClient;
import com.llly.client.ShoppingCarFeignClient;
import com.llly.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static io.lettuce.core.protocol.CommandKeyword.BY;

@RestController
public class ShopingCarController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ShoppingCarFeignClient shoppingCarFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;


    @RequestMapping("/addShopCar")
    public Map addShopCar(Integer pid, Integer number, HttpSession session){
        Map map=new HashMap();
            System.out.println("传递参数："+pid+"::::"+number);
        ShoppingCar shoppingCar=new ShoppingCar();
        shoppingCar.setPid(pid);
        shoppingCar.setNumber(number);

        Easybuy_user suser = (Easybuy_user) session.getAttribute("user");
        shoppingCar.setUid(suser.getId());
        System.out.println("登录用户信息："+suser);

        System.out.println("消费者：用户登录后添加购物车："+shoppingCar);
        int num = shoppingCarFeignClient.addShoppingCar(shoppingCar);

        if(num>0){
            //查询该用户下面，刚刚新增购物车信息
            Map<String, Object> map1 = shoppingCarFeignClient.showAllShoppingCar(suser.getId());
            //修改库存
            shoppingCarFeignClient.xiugaikucun(number,pid);

            map.put("scs",map1.get("cars"));
            map.put("zj",map1.get("zj"));


            map.put("mess","添加成功");
        }else{
            map.put("mess","添加失败");
        }
        return map;
    }

    @RequestMapping("/jiesuan1")
    public ModelAndView jiesuan1(ModelAndView mv,HttpSession session){
        Easybuy_user user = (Easybuy_user) session.getAttribute("user");
        Integer uid = user.getId();
        //购物车
        Map<String, Object> map = shoppingCarFeignClient.showAllShoppingCar(uid);
        if (map!=null){
            List<ShoppingCar> shoppingCars= (List<ShoppingCar>) map.get("cars");
            mv.addObject("snum",shoppingCars.size());
            mv.addObject("zj",map.get("zj"));
            mv.addObject("shopcars",shoppingCars);
        }else{
            mv.addObject("snum",0);
            mv.addObject("zj",0);
        }
        //商品分类部分
        List<Easybuy_product_category> allEpcs = productFeignClient.findAllEpcs();   //左侧分类栏及商品
        mv.addObject("epcs",allEpcs);
        mv.setViewName("BuyCar");
        return mv;
    }

    @RequestMapping("/jiesuan2")
    public ModelAndView jiesuan2(ModelAndView mv,HttpSession session){
        Easybuy_user user = (Easybuy_user) session.getAttribute("user");
        Integer uid = user.getId();
        //商品分类部分
        List<Easybuy_product_category> allEpcs = productFeignClient.findAllEpcs();   //左侧分类栏及商品
        mv.addObject("epcs",allEpcs);

        Map<String, Object> map = shoppingCarFeignClient.showAllShoppingCar(uid);
        if (map!=null){
            List<ShoppingCar> shoppingCars= (List<ShoppingCar>) map.get("cars");
            mv.addObject("snum",shoppingCars.size());
            mv.addObject("zj",map.get("zj"));
            mv.addObject("shopcars",shoppingCars);
        }else{
            mv.addObject("snum",0);
            mv.addObject("zj",0);
        }
        mv.addObject("address",shoppingCarFeignClient.getaddress(uid));
        mv.setViewName("BuyCar_Two");
        return mv;
    }

    @RequestMapping("/jiesuan3")
    public ModelAndView jiesuan3(ModelAndView mv, String address,String remark,Integer selectadd,
                                 float zj,HttpSession session){
        Easybuy_user user = (Easybuy_user) session.getAttribute("user");
        Integer uid = user.getId();

            System.out.println("8081的jiesuan3"+address+remark+selectadd);
            System.out.println("address"+address);

        //将订单号等信息存入order表中
        Easybuy_order order=new Easybuy_order();
        if (selectadd==null||selectadd==-1){
            if (address==null||address.equals("")){
                mv.addObject("message","请填写新的收货地址");
                mv.setViewName("forward:/jiesuan2");
                return mv;
            }else{
                shoppingCarFeignClient.addAddress(uid,address,remark);
                order.setUserAddress(address);
                mv.addObject("address",address);
                mv.setViewName("BuyCar_Three");
            }
        }else{
                mv.addObject("address",shoppingCarFeignClient.getaddress(uid).get(selectadd).getAddress());
                order.setUserAddress(shoppingCarFeignClient.getaddress(uid).get(selectadd).getAddress());
                mv.setViewName("BuyCar_Three");
        }

        //商品分类部分
        List<Easybuy_product_category> allEpcs = productFeignClient.findAllEpcs();   //左侧分类栏及商品
        mv.addObject("epcs",allEpcs);

        //获取订单号
//        int machineId = 1;//最大支持1-9个集群机器部署
//
//        int hashCodeV = UUID.randomUUID().toString().hashCode();
//                        UUID.randomUUID().toString().replace("-","").toLowerCase();
//        if(hashCodeV < 0) {//有可能是负数
//            hashCodeV = - hashCodeV;
//        }

        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r2=(int)(Math.random()*(10));
        int r3=(int)(Math.random()*(10));
        //  int r4=(int)(Math.random()*(10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        String paymentID =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(r3)+String.valueOf(now);
        mv.addObject("zjine",zj);
        mv.addObject("dingdanhao",paymentID);                                //订单号

        order.setUserId(user.getId());
        order.setLoginName(user.getLoginName());
        order.setCost(zj);
        order.setSerialNumber(paymentID);
        orderFeignClient.addOrder(order);

        //支付后将购物车中商品加入订单详情表中
        Map<String, Object> map = shoppingCarFeignClient.showAllShoppingCar(uid);
        List<ShoppingCar> shoppingCars1 = (List<ShoppingCar>) map.get("cars");
        ObjectMapper mapper=new ObjectMapper();
        List<ShoppingCar> cars = mapper.convertValue(shoppingCars1, new TypeReference<List<ShoppingCar>>() {
        });

        //for (ShoppingCar car:shoppingCars)
        for(int i=0;i<cars.size();i++) {
            //System.out.println("cccccccccc"+shoppingCars.get(i));
            ShoppingCar car=cars.get(i);
            Easybuy_order_detail easybuy_order_detail=new Easybuy_order_detail();
            easybuy_order_detail.setOrderId(paymentID);
            easybuy_order_detail.setProductId(car.getEp().getId());
            easybuy_order_detail.setQuantity(car.getNumber());
            easybuy_order_detail.setCost(car.getXiaoji());
            orderFeignClient.addOrderDetail(easybuy_order_detail);
        }
        //将购物车中商品isdelete改为1
        shoppingCarFeignClient.updateCar(uid);

        //最后再查一次购物车
        Map<String, Object> map2 = shoppingCarFeignClient.showAllShoppingCar(uid);
        if (map2!=null){
            List<ShoppingCar> shoppingCars2 = (List<ShoppingCar>) map2.get("cars");
            mv.addObject("snum",shoppingCars2.size());
            mv.addObject("zj",map2.get("zj"));
            mv.addObject("shopcars",shoppingCars2);
        }else{
            mv.addObject("snum",0);
            mv.addObject("zj",0);
        }
        return mv;
    }


    @RequestMapping("/updatenum")
    public ModelAndView updatenum(Integer pid,Integer number,HttpSession session,ModelAndView mv){
        System.out.println("ppppp"+pid+number);
        Map map = this.addShopCar(pid, number, session);
        mv.setViewName("forward:/jiesuan1");
        return mv;
    }

    @RequestMapping("/delCar")
    public ModelAndView delCar(Integer pid,Integer nums,HttpSession session,ModelAndView mv){
        Easybuy_user user = (Easybuy_user) session.getAttribute("user");
        Integer uid = user.getId();
        if (pid==null){
            pid=0;
        }
        shoppingCarFeignClient.delCar(uid,pid);
        shoppingCarFeignClient.xiugaikucun(-nums,pid);
        mv.setViewName("forward:/jiesuan1");
        return mv;
    }




}
